{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>酒龄分布分析 | WMS智能分析系统</title>
    <!-- Bootstrap 5 -->
    <link href="{% static 'plugins/bootstrap-5.3.0-alpha1-dist/css/bootstrap.min.css' %}" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root {
            --primary: #6366f1;
            --primary-light: #818cf8;
            --secondary: #8b5cf6;
            --light: #f8fafc;
        }

        body {
            background-color: #f5f7fb;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .card {
            border-radius: 12px;
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.08);
            border: none;
            margin-bottom: 25px;
            transition: transform 0.3s ease;
        }

        .card:hover {
            transform: translateY(-5px);
        }

        .card-header {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
            border-radius: 12px 12px 0 0 !important;
            padding: 15px 20px;
            font-weight: 600;
        }

        .chart-container {
            position: relative;
            height: 400px;
            padding: 20px;
        }

        .stats-card {
            background: white;
            border-left: 4px solid var(--primary);
        }

        .stats-value {
            font-size: 1.8rem;
            font-weight: 700;
            color: var(--primary);
        }

        .stats-label {
            font-size: 0.9rem;
            color: #64748b;
        }

        .nav-tabs .nav-link {
            color: #475569;
            font-weight: 500;
            border: none;
        }

        .nav-tabs .nav-link.active {
            color: var(--primary);
            border-bottom: 3px solid var(--primary);
            background: transparent;
        }

        .summary-section {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 25px;
        }

        .badge-age {
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 500;
        }

        .badge-30 { background-color: #dbeafe; color: #1d4ed8; }
        .badge-60 { background-color: #d1fae5; color: #047857; }
        .badge-90 { background-color: #fef3c7; color: #b45309; }
        .badge-90plus { background-color: #fee2e2; color: #b91c1c; }

        /* 新增表格样式 */
        .table-item-name {
            max-width: 180px;
            word-wrap: break-word;
        }

        .table-responsive {
            overflow-x: auto;
        }

        .table th {
            white-space: nowrap;
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <div class="d-flex align-items-center mb-4">
            <h3 class="mb-0 flex-grow-1">酒龄分布分析</h3>
            <a href="{% url 'aging_analysis_upload' %}" class="btn btn-primary">
                <i class="fas fa-upload me-2"></i>重新上传
            </a>
        </div>

        <!-- 统计摘要 -->
        <div class="summary-section">
            <div class="row">
                <div class="col-md-3 mb-3">
                    <div class="stats-card p-3">
                        <div class="stats-value" id="total-items">0</div>
                        <div class="stats-label">总物品数</div>
                    </div>
                </div>
                <div class="col-md-3 mb-3">
                    <div class="stats-card p-3">
                        <div class="stats-value" id="total-warehouses">0</div>
                        <div class="stats-label">仓库数量</div>
                    </div>
                </div>
                <div class="col-md-3 mb-3">
                    <div class="stats-card p-3">
                        <div class="stats-value" id="total-quantity">0</div>
                        <div class="stats-label">总库存量</div>
                    </div>
                </div>
                <div class="col-md-3 mb-3">
                    <div class="stats-card p-3">
                        <div class="stats-value" id="avg-aging">0</div>
                        <div class="stats-label">平均酒龄(天)</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 仓库选择导航 -->
        <ul class="nav nav-tabs mb-4" id="warehouseTabs" role="tablist">
            <!-- 动态生成仓库标签 -->
        </ul>

        <div class="tab-content" id="warehouseContent">
            <!-- 动态生成仓库内容 -->
        </div>

        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">酒龄分布分析</h5>
                <div>
                    <span class="badge badge-30 me-2">&#9679; &lt;30天</span>
                    <span class="badge badge-60 me-2">&#9679; 30-60天</span>
                    <span class="badge badge-90 me-2">&#9679; 60-90天</span>
                    <span class="badge badge-90plus">&#9679; ≥90天</span>
                </div>
            </div>
            <div class="card-body">
                <div class="chart-container">
                    <canvas id="agingChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener("DOMContentLoaded", function () {
            const rawData = JSON.parse('{{ grouped_data|escapejs }}');

            if (!rawData || rawData.length === 0) {
                alert("未接收到有效数据，请先上传库存文件进行分析");
                return;
            }

            // 1. 计算统计数据
            let totalItems = 0;
            let totalWarehouses = rawData.length;
            let totalQuantity = 0;
            let totalAging = 0;
            let itemCount = 0;

            rawData.forEach(warehouse => {
                totalItems += warehouse.items.length;
                warehouse.items.forEach(item => {
                    Object.values(item.intervals).forEach(value => {
                        totalQuantity += value;

                        // 计算平均酒龄的加权值
                        if (value > 0) {
                            let agingValue = 0;
                            if (item.intervals["<30天"] > 0) agingValue += 15 * item.intervals["<30天"];
                            if (item.intervals["30-60天"] > 0) agingValue += 45 * item.intervals["30-60天"];
                            if (item.intervals["60-90天"] > 0) agingValue += 75 * item.intervals["60-90天"];
                            if (item.intervals["≥90天"] > 0) agingValue += 120 * item.intervals["≥90天"];

                            totalAging += agingValue;
                            itemCount += value;
                        }
                    });
                });
            });

            // 更新统计信息
            document.getElementById('total-items').textContent = totalItems.toLocaleString();
            document.getElementById('total-warehouses').textContent = totalWarehouses.toLocaleString();
            document.getElementById('total-quantity').textContent = totalQuantity.toLocaleString();
            document.getElementById('avg-aging').textContent = itemCount > 0 ?
                (totalAging / itemCount).toFixed(1) : '0.0';

            // 2. 生成仓库导航标签
            const warehouseTabs = document.getElementById('warehouseTabs');
            const warehouseContent = document.getElementById('warehouseContent');

            rawData.forEach((warehouse, index) => {
                // 创建标签页
                const tabId = `warehouse-${index}`;

                // 标签页导航
                const navItem = document.createElement('li');
                navItem.className = 'nav-item';
                navItem.innerHTML = `
                    <a class="nav-link ${index === 0 ? 'active' : ''}"
                       id="${tabId}-tab"
                       data-bs-toggle="tab"
                       href="#${tabId}"
                       role="tab">
                       ${warehouse.warehouse}
                    </a>
                `;
                warehouseTabs.appendChild(navItem);

                // 标签页内容
                const tabPane = document.createElement('div');
                tabPane.className = `tab-pane fade ${index === 0 ? 'show active' : ''}`;
                tabPane.id = tabId;
                tabPane.role = 'tabpanel';

                // 创建仓库内物品表格
                let tableHTML = `
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead class="table-light">
                                <tr>
                                    <th>物品名称</th>
                                    <th class="text-center">&lt;30天</th>
                                    <th class="text-center">30-60天</th>
                                    <th class="text-center">60-90天</th>
                                    <th class="text-center">≥90天</th>
                                    <th class="text-center">总计</th>
                                    <th class="text-center">平均酒龄</th>
                                </tr>
                            </thead>
                            <tbody>
                `;

                warehouse.items.forEach(item => {
                    const total = Object.values(item.intervals).reduce((sum, val) => sum + val, 0);
                    const agingValue = (
                        (15 * item.intervals["<30天"] +
                        45 * item.intervals["30-60天"] +
                        75 * item.intervals["60-90天"] +
                        120 * item.intervals["≥90天"]) / total
                    ) || 0;

                    tableHTML += `
                        <tr>
                            <td class="table-item-name">${item.name}</td>
                            <td class="text-center">${item.intervals["<30天"].toLocaleString()}</td>
                            <td class="text-center">${item.intervals["30-60天"].toLocaleString()}</td>
                            <td class="text-center">${item.intervals["60-90天"].toLocaleString()}</td>
                            <td class="text-center">${item.intervals["≥90天"].toLocaleString()}</td>
                            <td class="text-center fw-bold">${total.toLocaleString()}</td>
                            <td class="text-center">
                                <span class="badge ${
                                    agingValue < 30 ? 'badge-30' :
                                    agingValue < 60 ? 'badge-60' :
                                    agingValue < 90 ? 'badge-90' : 'badge-90plus'
                                }">
                                    ${agingValue.toFixed(1)}天
                                </span>
                            </td>
                        </tr>
                    `;
                });

                tableHTML += `
                            </tbody>
                        </table>
                    </div>
                `;

                tabPane.innerHTML = tableHTML;
                warehouseContent.appendChild(tabPane);
            });

            // 3. 创建图表
            const ctx = document.getElementById('agingChart').getContext('2d');

            // 按仓库分组数据
            const warehouseNames = rawData.map(w => w.warehouse);
            const datasets = [
                {
                    label: '<30天',
                    data: rawData.map(w =>
                        w.items.reduce((sum, item) => sum + item.intervals["<30天"], 0)
                    ),
                    backgroundColor: 'rgba(75, 192, 192, 0.7)',
                    borderColor: 'rgba(75, 192, 192, 1)',
                    borderWidth: 1
                },
                {
                    label: '30-60天',
                    data: rawData.map(w =>
                        w.items.reduce((sum, item) => sum + item.intervals["30-60天"], 0)
                    ),
                    backgroundColor: 'rgba(54, 162, 235, 0.7)',
                    borderColor: 'rgba(54, 162, 235, 1)',
                    borderWidth: 1
                },
                {
                    label: '60-90天',
                    data: rawData.map(w =>
                        w.items.reduce((sum, item) => sum + item.intervals["60-90天"], 0)
                    ),
                    backgroundColor: 'rgba(255, 206, 86, 0.7)',
                    borderColor: 'rgba(255, 206, 86, 1)',
                    borderWidth: 1
                },
                {
                    label: '≥90天',
                    data: rawData.map(w =>
                        w.items.reduce((sum, item) => sum + item.intervals["≥90天"], 0)
                    ),
                    backgroundColor: 'rgba(255, 99, 132, 0.7)',
                    borderColor: 'rgba(255, 99, 132, 1)',
                    borderWidth: 1
                }
            ];

            new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: warehouseNames,
                    datasets: datasets
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        x: {
                            stacked: false,
                            title: {
                                display: true,
                                text: '仓库'
                            }
                        },
                        y: {
                            stacked: false,
                            title: {
                                display: true,
                                text: '库存数量'
                            },
                            beginAtZero: true
                        }
                    },
                    plugins: {
                        legend: {
                            position: 'top',
                        },
                        title: {
                            display: true,
                            text: '各仓库酒龄分布情况',
                            font: {
                                size: 16
                            }
                        },
                        tooltip: {
                            callbacks: {
                                footer: (tooltipItems) => {
                                    const warehouseIndex = tooltipItems[0].dataIndex;
                                    const warehouse = rawData[warehouseIndex];
                                    const itemNames = warehouse.items.map(item => item.name);
                                    const totalItems = warehouse.items.length;

                                    // 最大显示行数
                                    const maxLines = 5;
                                    const itemsPerLine = 3;

                                    // 创建换行显示的工具提示内容
                                    let footerContent = [
                                        `仓库物品数: ${totalItems}`,
                                        `仓库物品:`
                                    ];

                                    // 添加物品名称，每行最多3个
                                    let currentLine = [];
                                    let lineCount = 0;

                                    for (let i = 0; i < itemNames.length; i++) {
                                        currentLine.push(itemNames[i]);

                                        // 每3个物品换一行，或是最后一个物品
                                        if (currentLine.length === itemsPerLine || i === itemNames.length - 1) {
                                            footerContent.push(currentLine.join('、'));
                                            currentLine = [];
                                            lineCount++;

                                            // 达到最大行数时添加省略号
                                            if (lineCount >= maxLines && i < itemNames.length - 1) {
                                                const remaining = itemNames.length - i - 1;
                                                footerContent.push(`...及其他${remaining}件物品`);
                                                break;
                                            }
                                        }
                                    }

                                    return footerContent;
                                }
                            }
                        }
                    }
                }
            });
        });
    </script>

    <!-- Bootstrap JS -->
    <script src="{% static 'plugins/bootstrap-5.3.0-alpha1-dist/js/bootstrap.bundle.min.js' %}"></script>
</body>
</html>